

#include "FileSystemIndexer.h"

FileSystemIndexer::FileSystemIndexer(SearchEngine* engine) : engine(engine) {
    fileParser = new FileParser(engine);
}

void FileSystemIndexer::indexFs(std::vector<std::string> paths , int action,std::string& response) {
    for (std::vector<std::string>::const_iterator ite = paths.begin(); ite != paths.end(); ++ite) {
        std::string path = *ite;
        DIR* d = opendir(path.c_str());
        static struct dirent* dirp;
        std::vector<std::string> dirs;
        if (!d) {
            response+=std::string("Unable to open directory ")+path+std::string("/n");
            response+=std::string("Error is ")+std::string(strerror(errno))+std::string("(")+std::string(")")+std::string("/n");
            return;
        }
        while ((dirp = readdir(d)) != NULL) {
            if (0 == strcmp(".", dirp->d_name) ||
                    0 == strcmp("..", dirp->d_name)) continue; // skip . and ..
            std::string candidate(path + "/" + dirp->d_name);
            try {
                if (LinuxFileInfo::isRegularFile(candidate)) {
                    if (LinuxFileInfo::canRead(candidate)) {
                        if(action==0) {
                            fileParser->parse(candidate);
                        } else if (action==1){
                            //fileParser modificar
                        } else if(action==2) {
                            fileParser->removeDocuments(candidate);
                        }
                    }
                } else if (LinuxFileInfo::isDirectory(candidate)) {
                    dirs.push_back(candidate);
                }
            } catch (const invalid_argument& ia) {
                response+=std::string("Caught exception on path")+candidate+std::string(":  ")+ia.what()+std::string("/n");
            }
        }
        closedir(d);
        this->indexFs(dirs,action,response);
    }
}

